package com.hellobike.haxing.modules.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.coupon.entity.Coupon;
import com.hellobike.haxing.modules.coupon.entity.UserCoupon;
import com.hellobike.haxing.modules.coupon.mapper.CouponMapper;
import com.hellobike.haxing.modules.coupon.mapper.UserCouponMapper;
import com.hellobike.haxing.modules.user.entity.User;
import com.hellobike.haxing.modules.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Description: c端用户信息
 * @Author: haxing-boot
 * @Date: 2021-01-11
 * @Version: V1.0
 */
@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController extends BaseController<User, IUserService> {
    @Autowired
    private IUserService userService;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private CouponMapper couponMapper;

    /**
     * 分页列表查询
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "c端用户信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(User user,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<User> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        Page<User> page = new Page<User>(pageNo, pageSize);
        IPage<User> pageList = userService.page(page, queryWrapper);
        return Result.ok(pageList);
    }


	//根据规则计算用户券有效期
	private LocalDateTime[] getUserCouponValidTimeRangeByRule(JSONObject rule) {
		LocalDateTime[] timeRange = new LocalDateTime[2];
		if (rule == null) {
			return timeRange;
		}
		if (rule.getInteger("type") == 1) {
			//固定时长，领取后n天内有效
			LocalDate today = LocalDate.now();
			timeRange[0] = today.atTime(0, 0, 0);
			timeRange[1] = today.plusDays(rule.getLongValue("validDays") - 1).atTime(23, 59, 59);
		} else if (rule.getInteger("type") == 2) {
			//固定期限
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			timeRange[0] = LocalDate.parse(rule.getString("validTime"), formatter).atTime(0, 0, 0);
			timeRange[1] = LocalDate.parse(rule.getString("expireTime"), formatter).atTime(23, 59, 59);
		}
		return timeRange;
	}

    @PostMapping(value = "sendCoupon")
    @AutoLog(value = "给用户发券")
    public Result<?> sendCoupon(@RequestBody UserCoupon userCoupon) {
		Coupon coupon = couponMapper.selectById(userCoupon.getCouponId());
		if(coupon == null) {
			return Result.error("券不存在");
		}
//绑定券到用户账户
		LocalDateTime[] validTimeRange = getUserCouponValidTimeRangeByRule(coupon.getTimeLimitRule());
		userCoupon.setStatus(0).setValidTime(validTimeRange[0]).setExpireTime(validTimeRange[1]);
		userCouponMapper.insert(userCoupon);
		return Result.ok("券发放成功");
    }

    /**
     * 添加
     *
     * @param user
     * @return
     */
    @AutoLog(value = "c端用户信息-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody User user) {
        userService.save(user);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param user
     * @return
     */
    @AutoLog(value = "c端用户信息-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody User user) {
        userService.updateById(user);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "c端用户信息-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        userService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "c端用户信息-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.userService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(user);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param user
     */
    @AutoLog(value = "c端用户信息-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, User user) {
        return super.exportXls(request, user, User.class, "c端用户信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "c端用户信息-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, User.class);
    }

}
